# -*- coding: utf-8 -*-
"""
__mktime__ = '2019/4/21'
__author__ = 'Just'
__filename__ = 'theme'
"""
from sqlalchemy import Column, Integer, String, orm, or_, SmallInteger
from app.libs.common import get_current_time
from app.libs.error_code import NotFoundException, ParameterException
from app.model.base import BaseModel, db


# 主题与漫画关联表
theme_comic = db.Table(
    'theme_comic',
    db.Column('id', db.Integer, primary_key=True, autoincrement=True),
    db.Column('tid', db.Integer, db.ForeignKey('theme.id')),
    db.Column('cid', db.Integer, db.ForeignKey('comic.cid'))
)


class Theme(BaseModel):
    """主题模型"""
    __tablename__ = 'theme'

    id = Column(SmallInteger, primary_key=True, autoincrement=True)
    title = Column(String(50), unique=True, comment='主题名称')
    description = Column(String(255), comment='主题简介')
    update_time = Column(Integer, comment='修改时间')

    # 多对多 我的漫画
    comics = db.relationship('Comic', secondary=theme_comic, backref=db.backref('themes', lazy='dynamic'), lazy='dynamic')

    @orm.reconstructor
    def __init__(self):
        # 序列化列表
        self.fields = ['id', 'title',
                       'description', 'update_time',
                       'create_time', 'status'
                       ]

    @staticmethod
    def get_theme_list():
        """获取可用主题列表"""
        theme_list = Theme.query.filter(Theme.status == 1).all()
        return theme_list

    @staticmethod
    def get_list_for_admin():
        """管理员获取主题列表"""
        theme_list = Theme.query.all()
        return theme_list

    @staticmethod
    def add_theme(params):
        """添加主题记录"""
        has = Theme.query.filter(Theme.title == params['title']).first()
        if has:
            raise ParameterException('已经存在同名Theme, 添加失败', error_code=4011)
        else:
            with db.auto_commit():
                # 添加
                theme = Theme()
                theme.title = params['title']
                theme.description = '未添加描述信息' if params['description'] is None else params['description']
                theme.update_time = get_current_time()
                db.session.add(theme)

    @staticmethod
    def update_theme(tid, params):
        # 更新
        theme = Theme.query.get_or_404(tid, msg='此id号 theme栏不存在', error_code=4000)
        with db.auto_commit():
            if params['title'] != theme.name:
                theme.name = params['title']
            theme.description = '未添加描述信息' if params['description'] is None else params['description']
            theme.update_time = get_current_time()
